package com.ysq.www.api.work.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysq.www.api.user.entity.User;
import com.ysq.www.api.user.mapper.UserMapper;
import com.ysq.www.api.work.entity.Approve;
import com.ysq.www.api.work.entity.CopyTo;
import com.ysq.www.api.work.entity.GeneralTask;
import com.ysq.www.api.work.mapper.ApproveMapper;
import com.ysq.www.api.work.mapper.CopyToMapper;
import com.ysq.www.api.work.mapper.GeneralTaskMapper;
import com.ysq.www.api.work.service.IGeneralTaskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysq.www.common.result.ResultMsg;
import com.ysq.www.common.utils.Comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 通用任务表 服务实现类
 * </p>
 *
 * @author dql
 * @since 2020-08-11
 */
@Service
public class GeneralTaskServiceImpl extends ServiceImpl<GeneralTaskMapper, GeneralTask> implements IGeneralTaskService {

    private static final Logger log = LoggerFactory.getLogger(GeneralTaskServiceImpl.class);

    @Autowired
    private GeneralTaskMapper generalTaskMapper;

    @Autowired
    private ApproveMapper approveMapper;

    @Autowired
    private CopyToMapper copyToMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 提交通用任务
     * @param gk 通用任务对象
     * @return
     */
    @Override
    @Transactional
    public ResultMsg addGeneralTask(GeneralTask gk) {
        gk.setCreateTime(Comm.getNow());
        gk.setCheckStatus(0);
        gk.setUpdateTime(Comm.getNow());
        gk.setStatus(0);
        boolean save = this.save(gk);
        if (save){//创建审批记录
            Approve app = new Approve();
            app.setType(5);//类型为通用任务
            app.setContentId(gk.getId());
            app.setCheckId(gk.getApproverId());
            app.setSupperId(0);
            app.setLowerId(0);
            app.setCheckTime(Comm.getNow());
            app.setCheckStatus(0);
            app.setCreateTime(Comm.getNow());
            app.setStatus(0);
            approveMapper.insert(app);

            //创建抄送记录
            String copyIds = gk.getCopyIds();
            if (!StringUtils.isEmpty(copyIds)){
                List<CopyTo> cList = new ArrayList<>();
                String[] copyId = copyIds.split(";");
                for (String c : copyId) {
                    CopyTo ct = new CopyTo();
                    ct.setType(4);//通用任务
                    ct.setContentId(gk.getId());//内容id
                    ct.setUserId(Integer.parseInt(c));//抄送至用户的id
                    ct.setCreateTime(Comm.getNow());//创建时间
                    ct.setStatus(0);
                    cList.add(ct);
                }
                if (cList.size() > 0){
                    //copyToMapper.insertList(cList);
                    copyToMapper.insertListByNote(cList);
                }
            }
            return ResultMsg.INSERT_SUCCESS.setNewMsg("提交成功");
        }else return ResultMsg.INSERT_ERROR.setNewMsg("提交失败,内部错误");
    }

    /**
     * 查询我发起的通用任务
     * @param userId 用户id
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return
     */
    @Override
    public IPage<GeneralTask> selectSponsorById(Integer userId, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<GeneralTask> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).eq("user_id",userId);
        if (!StringUtils.isEmpty(time)){
            String startTime = time + " 00:00:00";
            String endTime = time + " 23:59:59";
            wrapper.between("create_time",startTime,endTime);
        }
        wrapper.orderByDesc("create_time");
        Page<GeneralTask> page = new Page<>(pageNumber,pageSize);
        IPage<GeneralTask> gPage = generalTaskMapper.selectPage(page, wrapper);
        return gPage;
    }

    /**
     * 分页查询待处理/已处理通用任务
     * @param userId 审批人用户id
     * @param type 类型：0未处理，1已处理
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return
     */
    @Override
    public IPage<GeneralTask> selectPendingByPage(Integer userId, Integer type, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<GeneralTask> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).eq("approver_id",userId);
        if (type == 0) wrapper.eq("check_status",0);
        else if (type == 1){
            wrapper.ne("check_status",0).ne("check_status",3);
            if (!StringUtils.isEmpty(time)){
                String startTime = time + " 00:00:00";
                String endTime = time + " 23:59:59";
                wrapper.between("create_time",startTime,endTime);
            }
        }
        wrapper.orderByDesc("create_time");
        Page<GeneralTask> page = new Page<>(pageNumber,pageSize);
        IPage<GeneralTask> gPage = generalTaskMapper.selectPage(page, wrapper);
        return gPage;
    }

    /**
     * 查询我发起的通用任务详情
     * @param gtId 通用任务id
     * @return GeneralTask
     */
    @Override
    public GeneralTask selectDetailById(Integer gtId) {
        GeneralTask gt = generalTaskMapper.selectDetailById(gtId);
        return getPrincipalList(gt);
    }

    /**
     * 查询待处理/已处理/抄送通用任务详情
     * @param gtId 通用任务id
     * @return GeneralTask
     */
    @Override
    public GeneralTask selectDisposeById(Integer gtId) {
        GeneralTask gt = generalTaskMapper.selectDetailById(gtId);
        return getPrincipalList(gt);
    }


    /**
     * 处理通用任务请求
     * @param gtId 通用任务id
     * @param result 处理结果：1通过，2驳回
     * @return
     */
    @Override
    @Transactional
    public ResultMsg checkGeneralTaskById(Integer gtId, Integer result) {
        GeneralTask gt = generalTaskMapper.selectById(gtId);
        if (gt.getCheckStatus() != 0) return ResultMsg.UPDATE_ERROR.setNewMsg("处理失败，通用任务已处理或已撤销");
        gt.setCheckStatus(result);
        gt.setUpdateTime(Comm.getNow());
        this.updateById(gt);
        UpdateWrapper<Approve> wrapper = new UpdateWrapper<>();
        wrapper.set("check_time",Comm.getNow()).set("check_status",result).set("update_time",Comm.getNow()).
                eq("type",5).eq("content_id",gtId);
        approveMapper.update(null,wrapper);
        return ResultMsg.SUCCESS.setNewMsg("处理成功");
    }

    /**
     * 撤销通用任务
     * @param gtId 通用任务id
     * @return ResultMsg
     */
    @Override
    @Transactional
    public ResultMsg repealGeneralTaskById(Integer gtId) {
        GeneralTask gt = generalTaskMapper.selectById(gtId);
        if (gt.getCheckStatus() != 0) return ResultMsg.UPDATE_ERROR.setNewMsg("撤销失败，该任务已处理不能撤销");
        gt.setCheckStatus(3);//撤销
        gt.setUpdateTime(Comm.getNow());
        this.updateById(gt);
        UpdateWrapper<Approve> wrapper = new UpdateWrapper<>();
        wrapper.set("check_time",Comm.getNow()).set("check_status",3).set("update_time",Comm.getNow()).
                eq("type",5).eq("content_id",gtId);
        approveMapper.update(null,wrapper);
        return ResultMsg.SUCCESS.setNewMsg("撤销成功");
    }

    /**
     * 分页查询抄送至我的通用任务
     * @param userId 用户id
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return IPage
     */
    @Override
    public IPage<GeneralTask> selectCopyToMeByPage(Integer userId, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<CopyTo> cWrapper = new QueryWrapper<>();
        cWrapper.eq("status",0).eq("user_id",userId).eq("type",4);
        List<CopyTo> cList = copyToMapper.selectList(cWrapper);
        if (cList.isEmpty()) return null;
        List<Integer> idList = new ArrayList<>();
        for (CopyTo c : cList) {
            idList.add(c.getContentId());
        }
        QueryWrapper<GeneralTask> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).ne("check_status",3).in("id",idList);
        if (!StringUtils.isEmpty(time)){
            String startTime = time + " 00:00:00";
            String endTime = time + " 23:59:59";
            wrapper.between("create_time",startTime,endTime);
        }
        wrapper.orderByDesc("create_time");
        Page<GeneralTask> page = new Page<>(pageNumber,pageSize);
        return generalTaskMapper.selectPage(page,wrapper);
    }


    /**
     * 公用方法
     * 获取负责人信息和抄送人信息
     */
    public GeneralTask getPrincipalList(GeneralTask gt){
        //获取负责人id字符串
        String[] uArray = gt.getPrincipalIds().split(";");
        List<Integer> idList = new ArrayList<>();
        for (String s : uArray) {
            idList.add(Integer.parseInt(s));
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).in("id",idList);
        List<User> userList = userMapper.selectList(wrapper);
        gt.setReceiveList(userList);
        String copyIds = gt.getCopyIds();//抄送人id字符串
        if (StringUtils.isEmpty(copyIds)) return gt;
        String[] cArray = copyIds.split(";");
        List<Integer> cIdList = new ArrayList<>();
        for (String c : cArray) {
            cIdList.add(Integer.parseInt(c));
        }
        QueryWrapper<User> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("status",0).in("id",cIdList);
        List<User> copyList = userMapper.selectList(wrapper1);
        gt.setCopyList(copyList);
        return gt;
    }
}
